from flask import Blueprint, request, session, current_app
from models.img import ImageModel
from models.interestingplace import InterestingPlaceModel
from .images import delete_img_update, delete_img_delete
from utils import restful
from exts import db
from geopy.distance import geodesic

bp = Blueprint('place', __name__, url_prefix='/place')


# 2、根据id获取景点信息
@bp.route('/get/<int:pid>', methods=['GET'])
def get_place(pid):
    place = InterestingPlaceModel.query.get(pid)
    if place:
        res = place.to_dict()
        return restful.ok(data={'place': res})
    return restful.params_error()


# 3、根据页数获取景点信息
@bp.route('/getPage/<int:page>', methods=['GET'])
def get_places_page(page):
    res = []
    page_size = current_app.config['PLACE_PAGE_SIZE']
    offset = (page - 1) * page_size
    places = InterestingPlaceModel.query.offset(offset).limit(page_size).all()
    for e in places:
        place = e.to_dict()
        res.append(place)
    return restful.ok(data={'places': res})


# 4、创建新的景点信息
@bp.route('/create', methods=['POST'])
def create_places():
    data = request.json
    print(data)
    place_name = data.get('place_name')
    place_intro = data.get('place_intro')
    latitude = data.get('latitude')
    longitude = data.get('longitude')
    place_address = data.get('place_address')
    if place_name and place_intro and latitude and longitude and place_address:
        place = InterestingPlaceModel(place_name=place_name, place_intro=place_intro, latitude=latitude,
                                      longitude=longitude, place_address=place_address)
        if data.get('cover_img'):
            place.cover_img = data.get('cover_img')
        db.session.add(place)
        db.session.flush()
        images = []
        if data.get('imgs'):
            for u in data.get('imgs'):
                if u:
                    image = ImageModel(article_id=place.place_id, type='place', url=u)
                    images.append(image)
        db.session.add_all(images)
    else:
        return restful.params_error()
    db.session.commit()
    return restful.ok(message='上传成功!')


# 5、更新景点信息
@bp.route('/update/<int:place_id>', methods=['POST'])
def update_places(place_id):
    data = request.json
    data['place'] = place_id
    print(data)
    old_place = InterestingPlaceModel.query.get(place_id)
    if old_place:
        old_place.place_name = data.get('place_name') if data.get('place_name') else old_place.place_name
        old_place.place_intro = data.get('place_intro') if data.get('place_intro') else old_place.place_intro
        old_place.cover_img = data.get('cover_img') if data.get('cover_img') else old_place.cover_img
        old_place.latitude = data.get('latitude') if data.get('latitude') else old_place.latitude
        old_place.longitude = data.get('longitude') if data.get('longitude') else old_place.longitude
        old_place.place_address = data.get('place_address') if data.get('place_address') else old_place.place_address
        db.session.commit()
        # 删除图片，数据库和文件，调用 images.delete_img_update
        delete_img_update(place_id, 'place', data.get('imgs'), data.get('imgList'))
    else:
        return restful.params_error()
    return restful.ok(message="上传成功", data=str(place_id))


# 6、删除景点信息
@bp.route('/delete/<int:place_id>', methods=['DELETE'])
def delete_blog(place_id):
    old_place = InterestingPlaceModel.query.get(place_id)
    # 2、删除图片
    delete_img_delete(place_id, 'place')
    # 3、提交事务
    db.session.delete(old_place)
    db.session.commit()
    return restful.ok(message='删除成功')


# 7、获取最近的5个景点
@bp.route('/getClearest/<float:lat>/<float:lot>', methods=['GET'])
def get_clearest(lat, lot):
    total = []
    places = InterestingPlaceModel.query.all()
    for p in places:
        tmp = p.to_dict(latitude=lat, longitude=lot)
        total.append(tmp)
    if len(total) <= 5:
        return restful.ok(data={'places': total})
    else:
        total.sort(key=lambda x: x['distance'])
        return restful.ok(data={'places': total[0:5]})


